<?php
require_once('include/My/DbHelper.php');
require_once('include/My/User.php');
require_once('include/My/Email.php');

class Alert
{
    public function isActive($recordId)
    {
        $row = $this->getAlert($recordId);
        
        return !!$row;
    }
    
    public function getAlert($recordId)
    {
        $sql = "SELECT * FROM alerts WHERE bean_id = '$recordId' AND sent = 0 LIMIT 1";
        return DbHelper::fetchOne($sql);
    }
    
    public function getDate($recordId) 
    {
        $row = $this->getAlert($recordId);
        if (isset($row['date']) && !empty($row['date'])) {
            $date = strtotime($row['date']);
            return date('Y-m-d', $date);
        }
        
        return '';
    }


    public function createNew($data)
    {
        $row = array(
            'bean_id' => $data['record'],
            'module'  => $data['moduleName'],
            'date'    => $data['date'],
            'sent'    => 0,
            'type'    => 'user'
        );

        DbHelper::insert($row, 'alerts');
        return $row;
    }
    
    public function update($post)
    {
        $data  = array('date' => $post['date']);
        $where = array('bean_id' => $post['record'], 'sent' => 0);
        
        return DbHelper::update('alerts', $data, $where);
    }
    
    public function insertAll($alerts)
    {
        if (!empty($alerts)) {
            foreach ($alerts as $alert) {
                DbHelper::insert($alert, 'alerts');
            }
        }
    }
    
    public function sendAll()
    {
        $this->sendAlerts('Accounts');
        $this->sendAlerts('Contacts');
        
        return true;
    }
    
    protected function sendAlerts($module)
    {
        if ($module == 'Accounts') {
            $sql = "SELECT al.bean_id, a.assigned_user_id, a.name FROM alerts al ";
            $sql.= " INNER JOIN accounts as a ON a.id = al.bean_id ";
        } else {
            $sql = "SELECT al.bean_id, con.assigned_user_id, CONCAT(con.first_name, ' ', con.last_name) as name FROM alerts al ";
            $sql.= " INNER JOIN contacts as con ON con.id = al.bean_id ";
        }
        
        $sql .= " WHERE UNIX_TIMESTAMP(DATE(al.date)) - UNIX_TIMESTAMP(CURDATE()) = 0
                AND al.sent = 0 AND al.module = '$module' ";
        
        $result = DbHelper::fetchAll($sql);
        
        if (!empty($result)) {
            $emailModel = new MyEmail();
            $emailUsers = UserHelper::getUsersEmail();
            
            foreach ($result as $row) {
                if (isset($emailUsers[$row['assigned_user_id']])) {
                    $emailMsg = $this->createMsg($row, $module);
                    $this->setAlertSent($row['bean_id']);
                    $emailModel->send(array($emailUsers[$row['assigned_user_id']]), 'Przypomnienie o aktywności', $emailMsg);
                } else {
                    $GLOBALS['log']->debug('Brak adresu email dla użytkownikao ID: '. $row['assigned_user_id'] . '('.$module.', '.$row['bean_id'].')');
                }
            }
        }
        
        return true;
    }
    
    protected function setAlertSent($beanId)
    {
        $values = array('sent' => 1);
        $where  = array('bean_id' => $beanId);
        
        DbHelper::update('alerts', $values, $where);
    }
    
    protected function createMsg(array $row, $module) 
    {
        if ($module == 'Accounts') {
            $msg = "Dla Klienta ";
        } else {
            $msg = "Dla Kontaktu ";
        }
        
        $msg .= "o nazwie: '" . $row['name'] . "' zostało ustawione przypomnienie o aktywności na dzisiejszy dzień.";
        
        return $msg;
    }
}